<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="480px" @confirm="handleSubmit" @close="handleClose">
            <el-form class="ls-form" ref="formRef" :rules="rules" :model="formData" label-width="100px">
                <el-form-item label="便签内容" prop="content">
                    <el-input
                    v-model="formData.content"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入便签内容"
                    maxlength="500"
                    show-word-limit
                />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { ref, reactive, shallowRef } from 'vue'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import { remarkAdd, remarkEdit } from '@/api/perms/role'
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const popupTitle = ref('添加便签')

// 便签列表数据
const noteList = ref([
    {
        id: 1,
        content: '这是一个测试便签',
        create_time: '2024-03-20 10:00:00'
    }
])

interface NoteItem {
    id: number;
    desc: string;
    create_time: string;
}

const formData = reactive({
    id: '' as string | number,
    content: ''
})

const rules = {
    content: [
        {
            required: true,
            message: '请输入便签内容',
            trigger: ['blur']
        }
    ]
}

// 添加便签

// 删除便签
const typeValue = ref('add')

const handleSubmit = async () => {
    await formRef.value?.validate()
    // TODO: 调用添加/编辑API
    // 编辑
    if (typeValue.value === 'edit') {
        await remarkEdit({
            id: formData.id,
            desc: formData.content
        })
    } else {
        await remarkAdd({
            desc: formData.content
        })
    }
    
    popupRef.value?.close()
    feedback.msgSuccess(formData.id ? '编辑成功' : '添加成功')
    emit('success', formData)
}

const handleClose = () => {
    emit('close')
}


// 打开弹窗
const open = (data: Partial<NoteItem> = {}, type: 'add' | 'edit' = 'add') => {
    popupRef.value?.open()
    if (type === 'edit') {
        formData.id = data.id || ''
        formData.content = data.desc || ''
    } else {
        formData.id = ''
        formData.content = ''
    }
    popupTitle.value = type === 'edit' ? '编辑便签' : '添加便签'
    typeValue.value = type
}

// const setFormData = async (data: Record<any, any>) => {
//     for (const key in formData) {
//         if (data[key] != null && data[key] != undefined) {
//             //@ts-ignore
//             formData[key] = data[key]
//         }
//     }
// }

defineExpose({
    open,
    // setFormData
})
</script>
